package com.itheima.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: taku
 * @CreateTime: 2020-04-26 16:34
 * @Description: 消息生产者
 */
public class Producer {

    public static void main(String[] args) {
        //1、创建链接工厂对象-factory=newConnectionFactory()
        try {
            ConnectionFactory factory = new ConnectionFactory();
            //2、设置RabbitMQ服务主机地址，默认localhost-factory.setHost("localhost")
            factory.setHost("localhost");
            //3、设置RabbitMQ服务端口，默认-1-factory.setPort(5672)
            factory.setPort(5672);
            //4、设置虚拟主机名字，默认/-factory.setVirtualHost("szitheima")
            factory.setVirtualHost("itheima");
            //5、设置用户连接名，默认guest-factory.setUsername("admin")
            factory.setPassword("admin");
            //6、设置链接密码，默认guest-factory.setPassword("admin")
            factory.setUsername("admin");
            //7、创建链接-connection=factory.newConnection()
            Connection connection = factory.newConnection();
            //8、创建频道-channel=connection.createChannel()
            Channel channel = connection.createChannel();
            //9、声明队列-channel.queueDeclare(名称，是否持久化，是否独占本连接,是否自动删除,附加参数)
            // queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
            //                                 Map<String, Object> arguments) throws IOException;
            channel.queueDeclare("simple_queue",true,false,false,null);
            //10、创建消息-Stringm=xxx
            String message = "hello world form simple queue";
            //11、消息发送-channel.basicPublish(交换机[默认DefaultExchage],路由key[简单模式可以传递队列名称],消息其它属性,消息内容)
            // String exchange, String routingKey, boolean mandatory, boolean immediate, BasicProperties props, byte[] body
            //
            for (int i = 0; i < 10; i++) {
                message = "hello world form simple queue + 第" + i + "条";
                channel.basicPublish("","simple_queue",null,message.getBytes());
            }
            //12、关闭资源-channel.close();connection.close()
            channel.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
